/**
 * weapp-js v1.7.1(2021-4-16)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2021 Motigo, Inc.
 * 
 */
import ConsoleLog from "./log.js";
import RequestCache from './request_cache.js';

export default {
    HOST: '',
    appid: wx.getAccountInfoSync().miniProgram.appId,
    user_openid: '',
    user_unionid: '',
    session_id: '',
    appVersion: '1.0.0',
    headers:{},
    init(session_id, appid, unionid, openid) { // init接口留着是兼容：之前的设计
        this._update_session(session_id, appid, openid, unionid);
    },
    set_host(host) {
        this.HOST = host;
    },
    setAppVersion(appVersion) {
        this.appVersion = appVersion;
    },
    setHeaders(headers){
        /*
            设置自定义请求头
         */
        if(headers && typeof headers == "object"){
            this.headers = Object.assign(this.headers,headers)
        }
    },
    // 禁用缓存：主要用于dev模式，外部统一禁用
    disable_cache() {
        RequestCache.disable();
    },
    get(path, params, enable_cache, expire_in) {
        return new Promise((resolve, reject) => {
            RequestCache.get(path, params, enable_cache).then(data => {
                resolve(data);
            }, () => {
                this._request('GET', path, params).then(data => {
                    if (enable_cache === true || expire_in) {
                        RequestCache.set(path, params, expire_in, data);
                    }
                    resolve(data);
                }, err => {
                    reject(err);
                });
            });
        })
    },
    post(path, params) {
        return this._request('POST', path, params);
    },
    put(path, params) {
        return this._request('PUT', path, params);
    },
    delete(path, params) {
        return this._request('DELETE', path, params);
    },
    ensure() {
        return new Promise(resolve => {
            if (this.HOST) {
                resolve()
            } else {
                let timer = setInterval(() => {
                    if (this.HOST) {
                        clearInterval(timer);
                        resolve();
                    }
                }, 10)
            }
        });
    },
    _update_session(session_id, appid, openid, unionid) {
        this.session_id = session_id;
        this.appid = appid;
        this.user_unionid = unionid;
        this.user_openid = openid;
    },
    _request(method, path, params) {
        let self = this;
        return new Promise((resolve, reject) => {
            self.ensure().then(() => {
                if(self.appid.length == 0){
                    let app = wx.getAccountInfoSync()
                    self.appid = app.miniProgram.appId
                }
                wx.request({
                    method: method,
                    timeout: 10000,
                    header: Object.assign(this.headers,{
                        'content-type': 'application/json',
                        'appid': self.appid,
                        'openid': self.user_openid,
                        'unionid': self.user_unionid,
                        'session': self.session_id,
                        'app-version': self.appVersion
                    }),
                    url: self.HOST + path,
                    data: params,
                    success(res) {
                        if (res.data.ret == 0) {
                            resolve(res.data.data);
                        } else {
                            reject(res.data);
                        }
                    },
                    fail(err) {
                        reject({
                            msg: err.errMsg
                        });
                        ConsoleLog.error("request fail!", err);
                    }
                })
            });
        });
    }
}